
import {get} from './api.js'


export const initMenu = (router,store) => {
    
    if(store.state.routes.length > 0){
        // console.log(222)
        return;
    }
    
    
    get('/system/cfg/menu').then(res => {
        if(res){
            //格式化Router
            let formatRouter = formatRouterData(res.data);
            //添加到Route
            console.log(formatRouter);
            router.addRoutes(formatRouter);
            //将数据存入Vuex
            store.commit('setRoutes',formatRouter);
            //连接WebSocket
            store.dispatch('connect');
            
        }
    })
}

export const formatRouterData = (routes) => {
    // console.log(routes);
    var formatRouters = [];
    routes.forEach(route => {
        let {
            path,
            component,
            name,
            iconCls,
            children,
        
        } = route;
        if(children && children instanceof Array){
            children = formatRouterData(children);
        }
        var fmRouter= {
            path:path,
            children:children,
            name:name,
            iconCls:iconCls,
            component(resolve){
                if(component.startsWith('Home')){
                    require(['../../views/'+component+'.vue'],resolve);
                }else if(component.startsWith('Emp')){
                    require(['../../views/emp/'+component+'.vue'],resolve);
                }else if(component.startsWith('Per')){
                    require(['../../views/per/'+component+'.vue'],resolve);
                }else if(component.startsWith('Sal')){
                    require(['../../views/sal/'+component+'.vue'],resolve);
                }else if(component.startsWith('Sys')){
                    require(['../../views/sys/'+component+'.vue'],resolve);
                }else if(component.startsWith('Sta')){
                    require(['../../views/sta/'+component+'.vue'],resolve);
                }
            }
        }
        formatRouters.push(fmRouter);
    })
    return formatRouters;
}